﻿using System;
using System.Data;
using System.Web.UI.HtmlControls;
using DevExpress.Web.ASPxTreeList;
using ITViet.Services;
using ITViet.Web.App_Code;
using System.Web.UI.WebControls;

namespace ITViet.Web.Pages
{
	public partial class Sitemap : BasePage
	{
		#region Events
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack && !IsCallback)
			{
				LoadTitle();
				LoadMainMenu();
			}

			if (IsCallback)
			{
				LoadMainMenu();
			}
		}
		#endregion

		#region Methods
		private void LoadMainMenu()
		{
			DataSet dsMainMenu = new MainMenuService().GetMainMenuByLanguage(CurrentLanguage.Id, MenuTypes.FrontEnd, null);
			if (dsMainMenu != null && dsMainMenu.Tables.Count > 0)
			{
				int count = 0;
				foreach (DataRow mainRow in dsMainMenu.Tables[0].Rows)
				{
					int id = Convert.ToInt32(mainRow["Id"]);
					string title = mainRow["Title"].ToString();
					string link = mainRow["Link"].ToString();
					TreeListNode treeNode = CreateNodeCore(count++, title, link, null);
					treeNode.Expanded = true;

					DataSet dsSubmenu = new SubMenuService().GetSubMenuByLanguage(id, CurrentLanguage.Id, null);
					if (dsSubmenu != null && dsSubmenu.Tables.Count > 0)
					{
						LoadSubMenu(dsSubmenu.Tables[0], ref count, treeNode);
					}
				}
			}
		}

		private void LoadSubMenu(DataTable table, ref int count, TreeListNode parentNode)
		{
			foreach (DataRow row in table.Rows)
			{
				int id = Convert.ToInt32(row["Id"]);
				string title = row["Title"].ToString();
				string link = row["Link"].ToString();
				string source = row["Source"].ToString();
				TreeListNode treeNode = CreateNodeCore(count++, title, link, parentNode);
				treeNode.Expanded = true;

				DataSet ds = new SubMenuService().GetSubMenuByParent(id, CurrentLanguage.Id, source);
				if (ds != null && ds.Tables.Count > 0)
				{
					LoadSubMenu(ds.Tables[0], ref count, treeNode);
				}
			}
		}

		TreeListNode CreateNodeCore(object key, string title, string link, TreeListNode parentNode)
		{
			TreeListNode node = tlSiteMap.AppendNode(key, parentNode);
			node["Title"] = title;
			node["Link"] = link;
			return node;
		}

		protected string GetUrl(TreeListDataCellTemplateContainer container)
		{
			return container.GetValue("Link").ToString();
		}

		private void LoadTitle()
		{
			Literal lrPageTitle = Master.FindControl("lrPageTitle") as Literal;
			if (lrPageTitle != null)
			{
				lrPageTitle.Text = Resources.Strings.Sitemap;
			}
		}
		#endregion
	}
}
